/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/


#include "MkHttp/MkHttpClient.h"
#include "MkHttp/MkHttpResponse.h"
#include "MkEvent/MkEvent.h"
#include "MkEvent/MkEventPool.h"
#include "MkEvent/MkTimer.h"
#include "MkUtil/MkLog.h"
#include <signal.h>
#include "MkUtil/MkBase64.h"

CMkTimer *g_pTimer = nullptr;
void SigHandle(int sig)
{
    if (sig == SIGINT&& g_pTimer) {
        g_pTimer->LoopBreak();
    }
};

int main(int argc, char ** argv)
{
#ifdef _WIN32
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    //signal(SIGPIPE, SIG_IGN);  //ignore sigpipe
    //signal(SIGPIPE, SIG_IGN);
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGPIPE);
    sigprocmask(SIG_BLOCK, &set, NULL);
#endif
    //MkLogInitLevel("http_client", TO_FILE);
    MkLogChangeLevel(LOG_DEBUG);
    signal(SIGINT, SigHandle);// 设置退出信号
    CMkEventPool Pool;
    Pool.Start();
    CMkTimer *g_pTimer = new CMkTimer;
    MkMap<MkString, MkString> MapHeader;
    MapHeader["Authorization"] = "Basic YWRtaW46YWRtaW4=";
    CMkHttpClient  *pClient = new  CMkHttpClient(Pool.GetFreeEvent(), g_pTimer, [](CMkTcpClient* pClient) {
        MkDelete(pClient);
    });
    MkString strBody;
    MkString Url = "ws://192.168.0.24:50081/file/aa.265.flv";
    //Url = "ws://192.168.100.120:50080/live/test5.live.flv";
    Url = "ws://127.0.0.1/live/111.flv";
    FILE *fp = fopen("1.dat", "wb");
    pClient->WebSocketConnect(Url, [pClient]() {
        //pClient->SendWebSocketMessage("aaaa");
    }, [fp](const Uint8* pBuf, Uint32 nLen) {
        fwrite(pBuf, 1, nLen, fp);
    }, [fp]() {
        fclose(fp);
    });
    g_pTimer->Dispatch();
    Pool.Stop();
    MkDelete(pClient);
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}

